package com.woniuxy.creditsystem.systemmag.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.woniuxy.creditsystem.annos.MyLog;
import com.woniuxy.creditsystem.common.bean.ResultMsg;
import com.woniuxy.creditsystem.common.bean.RoleInfo;
import com.woniuxy.creditsystem.common.mapper.RoleMapper;
import com.woniuxy.creditsystem.systemmag.service.IDownloadService;
import com.woniuxy.creditsystem.systemmag.service.IRoleService;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * 角色的增、删、查、改
 * @author hejie
 */
@Service
@Transactional(readOnly = true)
public class RoleServiceImpl implements IRoleService {

    @Resource
    private RoleMapper roleMapper;
    //用来把导出的excel信息，存储到download_info表中。供“下载中心”中下载该excel文件
    @Resource
    private IDownloadService downloadServiceImpl;
    /**
     * 新增角色
     * @author hejie
     * @param roleInfo
     * @return
     */
    @MyLog(value = "新增角色")
    @Transactional(isolation = Isolation.REPEATABLE_READ,rollbackFor = Exception.class)
    @Override
    public int saveRoleInfo(RoleInfo roleInfo) {
        return roleMapper.saveRoleInfo(roleInfo);
    }

    /**
     * 修改角色
     * @author hejie
     * @param RoleInfo
     * @return
     */
    @MyLog(value = "修改角色")
    @Transactional(isolation = Isolation.REPEATABLE_READ,rollbackFor = Exception.class)
    @Override
    public int updateRoleInfo(RoleInfo RoleInfo) {
        return roleMapper.updateRoleInfo(RoleInfo);
    }

    /**
     * 查询所有的角色
     * @author hejie
     * @return
     */
    @Override
    public List<RoleInfo> findAll() {
        return roleMapper.findAll();
    }

    /**
     * 分页查询（同时具有 模糊查询功能--动态sql）
     * @author hejie
     * @param RoleInfo 条件
     * @return
     */
//    @MyLog(value = "对角色表分页查询")
    @Override
    public PageInfo<RoleInfo> findAllByParams(int pageNum,int pageSize, RoleInfo RoleInfo) {
        return PageHelper.startPage(pageNum,pageSize).
                doSelectPageInfo(()->roleMapper.findAllByParams(RoleInfo));
    }

    /**
     * 删除一个RoleInfo
     * @author hejie
     * @param id
     * @return
     */
    @MyLog(value = "删除角色")
    @Transactional(isolation = Isolation.REPEATABLE_READ,rollbackFor = Exception.class)
    @Override
    public int deleteRoleInfo(Long id) {
        return roleMapper.deleteRoleInfo(id);
    }

    /**
     * 根据 角色id，查询菜单名称和该菜单的操作权限
     * @author hejie
     * @param id
     * @return
     */
    @Override
    public List<Map> findPermissionByRoleId(Long id) {
        return roleMapper.findPermissionByRoleId(id);
    }

    /**
     * 把页面传回来的table数据，写入到excel文件中
     * @author hejie
     * @param tableDataJson 前端的表格数据
     * @param path excel文件存放的路径（Dir）
     * @param simpleFileNameUserSet 用户设置的excel文件名
     * @return
     */
    @MyLog(value = "POI，导出角色管理查询结果为excel文件")
    @Transactional(isolation = Isolation.REPEATABLE_READ, rollbackFor = Exception.class)
     public ResultMsg write2excel(List<RoleInfo> tableDataJson, String path, String simpleFileNameUserSet) throws IOException{
         if (tableDataJson==null){
             return new ResultMsg(201,"页面表格内容为空，没有数据可以导出！",null);
         }

         //创建表对象，即工作簿对象
         HSSFWorkbook workbook = new HSSFWorkbook();
         //第一个sheet对象demo1
         HSSFSheet sheet = workbook.createSheet("demo1");
         //行对象
         HSSFRow row = sheet.createRow(0);
         //单元格对象
         HSSFCell cell0 = row.createCell(0);
         cell0.setCellValue("角色名称");
         HSSFCell cell1 = row.createCell(1);
         cell1.setCellValue("状态");
         HSSFCell cell2 = row.createCell(2);
         cell2.setCellValue("创建人");
         HSSFCell cell3 = row.createCell(3);
         cell3.setCellValue("创建时间");

         //解决日期显示不正常的问题：给第1行、第2列单元格写入日期
         //用Excel表对象获取CreationHelper对象
         CreationHelper createHelper = workbook.getCreationHelper();
         //用Excel表对象创建CellStyle对象
         CellStyle cellStyle = workbook.createCellStyle();
         //给cellStyle对象设置Date格式
         cellStyle.setDataFormat(createHelper.createDataFormat().getFormat("yyyy-MM-dd HH:mm:ss"));

         for (int i=0; i<tableDataJson.size(); i++){
             //行对象
             HSSFRow r = sheet.createRow(1+i);
//             for (int j=0; j<6; j++){
                 //单元格对象
                 HSSFCell cellRoleDesc = r.createCell(0);
                 cellRoleDesc.setCellValue(tableDataJson.get(i).getRoleDesc());
                 HSSFCell cellStatus = r.createCell(1);
                 String status="";
                 if (tableDataJson.get(i).getStatus()==1){
                     status="已启用";
                 }else {
                     status="已禁用";
                 }
                 cellStatus.setCellValue(status);
                 HSSFCell cellCreator = r.createCell(2);
                 cellCreator.setCellValue(tableDataJson.get(i).getCreateor());

                 HSSFCell cellCreateTime = r.createCell(3);
                 //设置 “Date”类型的显示格式
                 cellCreateTime.setCellStyle(cellStyle);
                 cellCreateTime.setCellValue(tableDataJson.get(i).getCreateTime());
//             }
         }

         FileOutputStream os = null;
        //fileName是excel文件名字：包含了“.excel”，该路径需要存到的“download_info表”的“file_path”字段
        //不含后缀名“.xls”
        String simpleFileName= "角色管理" + System.currentTimeMillis();
        if (simpleFileNameUserSet!=null && !("".equals(simpleFileNameUserSet))){
            simpleFileName=simpleFileNameUserSet;
        }
        String filePathName = path +File.separator + simpleFileName + ".xls";
         File file=new File(path);
         if (!file.exists()){
             file.mkdirs();
         }
         try {
             os = new FileOutputStream(filePathName);
         } catch (FileNotFoundException e) {
             e.printStackTrace();
         }
         //		workbook1.write(os);
         try {
             workbook.write(os);
         } catch (IOException e) {
             e.printStackTrace();
         }
         os.flush();
         os.close();

        //把 文件名+后缀 放到ResultMsg的data中返回，方便：“新增下载”时，能够直接自动开始下载，而不用费力去“下载中心”点击“下载”
         ResultMsg resultMsg=  new ResultMsg(200,"页面表格数据已经写入到"+filePathName,simpleFileName + ".xls");

        //把当前“下载中心”记录写入到数据库download_info
        //simpleFileName是excel名字，不含后缀名 （存储到download_info表中的excel文件名是 simpleFileName.xsl，simpleFileName是变量）
        downloadServiceImpl.saveExcelInfo2downloadInfo(simpleFileName);
         return resultMsg;
    }
}
